﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using PhotoAlbums.Models;
using PhotoAlbums.Models.VO;
using System.Data.Entity.Infrastructure;
using System.Collections.Generic;

namespace PhotoAlbums.Controllers
{
    public class CatalogController : Controller
    {
        private PhotoAlbumsDB db = new PhotoAlbumsDB();

        // GET: Catalog
        public ActionResult Index()
        {
            // 未登录跳转
            if(Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            int userId = (int)Session["id"];
            var catalogs = db.UserCatalog.Include(u => u.Catalog).Where(u => u.UserId == userId);
            
            return View(catalogs.ToList());
        }

        // GET: Catalog/Add
        public ActionResult Add()
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            ViewBag.UserId = (int)Session["id"];

            return View();
        }

        /*
        * @Title: Catalog/Add
        * @Doc: 用户添加目录
        * @param UserId 用户ID
        * @param Name 目录名字
        * @param CoverPath 目录封面图路径
        * @param Introduction 目录介绍
        */
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add([Bind(Include = "UserId,Name,CoverPath,Introduction")] CatalogVO catalogVO)
        {
            if (ModelState.IsValid)
            {
                int result = db.AddCatalogToUser(catalogVO.UserId, catalogVO.Name, catalogVO.CoverPath, catalogVO.Introduction, DateTime.Now, DateTime.Now);
                return RedirectToAction("Index");
            }
            return View();
        }

        // GET: Catalog/Edit/5
        public ActionResult Edit(int? id)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断参数
            if (id == null)
            {
                return RedirectToAction("Error", "Home", new { msg = "请求参数丢失" });
            }

            // 判断是否为自己的目录
            List<UserCatalog> userCatalogs = db.UserCatalog.Where(u => u.CatalogId == id).ToList();
            if (userCatalogs == null || userCatalogs.Count != 1 || userCatalogs[0].UserId != (int)Session["id"])
            {
                return RedirectToAction("Login", "User");
            }

            Catalog catalog = db.Catalog.Find(id);

            if (catalog == null)
            {
                return HttpNotFound();
            }

            return View(catalog);
        }

        // POST: Catalog/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,CoverPath,Introduction,UpdateTime,CreateTime")] Catalog catalog)
        {
            if (ModelState.IsValid)
            {
                // 数据打包
                catalog.UpdateTime = DateTime.Now;

                db.Entry(catalog).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(catalog);
        }

        // GET: Catalog/Delete/5
        public ActionResult Delete(int? id)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断参数
            if (id == null)
            {
                return RedirectToAction("Error", "Home", new { msg = "请求参数丢失" });
            }

            // 判断是否为自己的目录
            List<UserCatalog> userCatalogs = db.UserCatalog.Where(u => u.CatalogId == id).ToList();
            if (userCatalogs == null || userCatalogs.Count != 1 || userCatalogs[0].UserId != (int)Session["id"])
            {
                return RedirectToAction("Login", "User");
            }

            Catalog catalog = db.Catalog.Find(id);

            if (catalog == null)
            {
                return HttpNotFound();
            }

            return View(catalog);
        }

        // POST: Catalog/Delete/5
        /*
         * 1、查找目录下是否有图片
         * 2、有则无法删除
         * 3、没有可以删除，先删与user的关联，再删catalog自身记录
         */
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            List<CatalogPhoto> catalogPhotos = db.CatalogPhoto.Where(c => c.CatalogId == id).ToList();

            // 判断是否可删除
            if(catalogPhotos == null || catalogPhotos.Count != 0) {
                return RedirectToAction("Error", "Home", new { msg = "此目录不可删除" });
            }

            // 先删与user的关联
            List<UserCatalog> userCatalogs = db.UserCatalog.Where(u => u.CatalogId == id).ToList();
            if(userCatalogs == null || userCatalogs.Count != 1)
            {
                return RedirectToAction("Error", "Home", new { msg = "此目录不可删除" });
            }
            db.UserCatalog.Remove(userCatalogs[0]);

            // 再删catalog自身记录
            Catalog catalog = db.Catalog.Find(id);
            db.Catalog.Remove(catalog);

            // 执行操作
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
